import React, { Component } from 'react'
import { Query } from 'react-apollo'

export default (WrappedComponent, mapDataToProps) => ({ query, children, ...otherProps }) => {
  if (!query) return <WrappedComponent {...otherProps}>{children}</WrappedComponent>
  return (
    <Query query={query.query} variables={query.variables}>
      {({ loading, error, data }) => {
        if (loading) return 'Loading...'
        if (error) return `Error! ${error.message}`
        return (
          <WrappedComponent {...otherProps} {...mapDataToProps(query.getData(data))}>
            {children}
          </WrappedComponent>
        )
      }}
    </Query>
  )
}
